﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/8/4 15:09:03
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using MyWebApp.Helper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using static MyWebApp.Helper.JwtHelper;

namespace MyWebApp.Filter
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class MyAuthorizeFilterAttribute : Attribute, IAuthorizationFilter //IActionFilter
    {

        #region IActionFilter 操作过滤器实现

        /// <summary>
        /// Action执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
        /// <summary>
        /// Action执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var authHeader = context.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(authHeader))
            {
                //var json =  JsonConvert.SerializeObject(new OperationResult(OperationResultType.Error, "保存失败"));
                //此接口必须携带token访问！
                context.Result = new ContentResult()
                {

                    Content = "此接口必须携带token访问，请登录携带Token访问",
                    ContentType = "text/html"//application/json
                };
            }
            else //字段值不为空
            {
                authHeader = authHeader.ToString().Replace("Bearer", "").Trim();//去掉Bearer字串
                if (authHeader == "")
                {
                    context.Result = new ContentResult()
                    {
                        Content = "token验证失败：您没有权限调用此接口，请登录重新获取Token",
                        ContentType = "text/html"
                    };
                }
                else
                {
                    LoginUserInfo LoginInfo = JwtHelper.GetJwtDecode(authHeader);
                    string UserName = LoginInfo.username;
                    string PassWord = LoginInfo.pwd;
                    double ExpireTimeStamp = LoginInfo.exp;
                    if (isTokenExpire(ExpireTimeStamp)) //这里应该验证有效期
                    {
                        //token验证失败：您没有权限调用此接口，请登录获取Token
                        context.Result = new ContentResult()
                        {
                            Content = "token验证失败：您没有权限调用此接口，请登录重新获取Token",
                            ContentType = "text/html"
                        };
                    }
                }

            }
        }
        #endregion

        #region IAuthorizationFilter 授权过滤器 

        /// <summary>
        /// 授权过滤器实现方法
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var authHeader = context.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(authHeader))
            {
                //var json =  JsonConvert.SerializeObject(new OperationResult(OperationResultType.Error, "保存失败"));
                //此接口必须携带token访问！
                context.Result = new ContentResult()
                {

                    Content = "此接口必须携带token访问，请登录携带Token访问",
                    ContentType = "text/html"//application/json
                };
            }
            else //字段值不为空
            {
                authHeader = authHeader.ToString().Replace("Bearer", "").Trim();//去掉Bearer字串
                if (authHeader == "")
                {
                    context.Result = new ContentResult()
                    {
                        Content = "token验证失败：您没有权限调用此接口，请登录重新获取Token",
                        ContentType = "text/html"
                    };
                }
                else
                {
                    LoginUserInfo LoginInfo = JwtHelper.GetJwtDecode(authHeader);
                    string UserName = LoginInfo.username;
                    string PassWord = LoginInfo.pwd;
                    double ExpireTimeStamp = LoginInfo.exp;
                    if (isTokenExpire(ExpireTimeStamp)) //这里应该验证有效期
                    {
                        //token验证失败：您没有权限调用此接口，请登录获取Token
                        context.Result = new ContentResult()
                        {
                            Content = "token验证失败：您没有权限调用此接口，请登录重新获取Token",
                            ContentType = "text/html"
                        };
                    }
                }

            }
        }
        #endregion
        /// <summary>
        /// 时间戳字符串
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        private bool isTokenExpire(double timestamp)
        {
            try
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                var expireTime = startTime.AddSeconds(timestamp);
                if (expireTime > DateTime.Now)
                {
                    return false;//未过期
                }
                else
                {
                    return true;//已过期
                }
            }
            catch (Exception ex)
            {
                return true;
            }
        }

    }
}
